#include <xc.h>

void initADC(void);
void initDAC(void);
void initIO(void);

// Look at microchip language tools libraries.

int main (void) {
	
	initADC(void);
	
	
	while(1) {
		
		ADCON1bits.SAMP = 1; // Start sampling
		Delay_ms(100); // Allow time to sample;
		ADCON1bits.SAMP = 0; // Clear sample bit, start conversion.
		while(ADCON1bits.DONE == 0)
			asm nop;	// Wait for DONE bit on ADCON1.
		// Do something here.
	}
	
	
	
	
}

// According to the datasheet the following needs to be done:
// 1. Select port pins as analog inputs (AD1PCFGH<15:0> or AD1PCFGL<15:0>)
// 2. Select voltage reference source to match expected range.
// 		(AD1CON2<15:13>)
// 3. Select analog conversion clock to match desired data rate
//		(AD1CON3<7:0>)
// 4. Determine how many S/H channels are used.
// 		(AD1CON2<9:8> and AD1PCFGH or AD1PCFGL)
// 5. Select sample/conversion sequence
// 		(AD1CON1<7:5> and AD1CON3<12:8>
// 6. Select how results are presented in buffer
// 		(AD1CON1<9:8>)
// 7. Turn on ADC modue. (AD1CON1<15>)

// Then, set up ADC interrupt.
// 1. Clear AD1IF bit
// 2. Select ADC interrupt priority.

// Page 256 of datasheet

void initADC(void) {
	AD1CON1bits.ADON = 0; // Turn off ADC.
	AD1CON1bits.ADSIDL = 1; // Turn module off when device idles.
	AD1CON1bits.AD12B = 0; // 10 bit, 4 channel ADC operation.
	AD1CON1bits.FORM = 0b11; // Output is signed fractional. 
	AD1CON1bits.SSRC = 0b111; // Internal counter ends sampling and 
							// starts conversion. Auto-convert.
	AD1CON1bits.ASAM = 0; // Sampling begins when SAMP bit is set.
	
	AD1CON2bits.VCFG = 0b000; // Reference voltages are AVdd and AVss.
	AD1CON2bits.CHPS = 0b00; // Converts channel 0.
	
	AD1CON3bits.ADRC = 0; // Clock derived from system clock.
	// I don't know what this impacts at the moment. This is the conversion
	// clock select bits.
	AD1CON3bits.ADCS = 0b00000001;// = Tcy * (ADCS bits +1) = 2 *Tcy = Tad.
	
	
	// AD1CHS0 is the ADC1 input channel 0 select register.
	
	// These define pins.
	AD1CHS0bits.CH0SB = 0b00000; // Channel 0 positive input is AN0
								 // for sample B bits?
	AD1CHS0bits.CH0SA = 0b00000; // Channel 0 positive input is AN0 
								 // for sample A bits?
								
	AD1CHS0bits.CH0NA = 1; // Channel 0 negative input is AN1. 0 is Vref-.
	
	AD1CHS0bits.PCFG = 0x1; // Channel 0 is sampled and converted.
	
	
	// Turn it on.
	ADCON1.ADON = 1;
}

void initDAC(void) {
	
	
}


void initIO(void) {
	
	
}
